<template>
  <div class="about">
    <div class="about-head">
      <div class="about-head_left">
        <SearchCascader
          v-model:value="selectedValue"
          :options="treeData"
          @search="handleSearch"
          @reset="handleReset"
        ></SearchCascader>
      </div>
      <div class="about-head_right">
        <a-space>
          <a-button type="primary" style="border-radius: unset;">
            <template #icon><form-outlined /></template>
            从模板导入
          </a-button>
          <a-button type="primary" style="border-radius: unset;" @click="handleAddRoot">
            <template #icon><plus-outlined /></template>
            新增
          </a-button>
          <a-button style="border-radius: unset;" @click="exportData">
            <template #icon><cloud-download-outlined /></template>
            导出
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="about-content">
      <TreeTableView
        :tree-data="treeData"
        :filter-value="filterValue"
        @add-child="handleAddChild"
        ref="treeTable"
      >
      </TreeTableView>
    </div>
  </div>

    <a-modal
    v-model:open="addModalVisible"
    :title="modeTitle"
    @ok="handleAddConfirm"
    @cancel="handleAddCancel"
  >
    <a-form
      :model="newNodeForm"
      :label-col="{span: 6}"
    >
      <a-form-item label="组织名称" required>
        <a-input v-model:value="newNodeForm.label"></a-input>
      </a-form-item>
      <a-form-item label="组织标识" required>
        <a-input v-model:value="newNodeForm.value" placeholder="请输入唯一组织标识"></a-input>
      </a-form-item>
      <a-form-item label="备注">
        <a-input v-model:value="newNodeForm.note"></a-input>
      </a-form-item>
      <a-form-item label="上级组织" v-if="newNodeForm.mode === 'child'">
        <a-input v-model:value="newNodeForm.parentLabel" disabled></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang='ts' setup>
import {
  FormOutlined,
  PlusOutlined,
  CloudDownloadOutlined
} from '@ant-design/icons-vue';
import SearchCascader from '@/components/SearchCascader.vue';
import TreeTableView from '@/components/TableTreeView.vue';
import { computed, ref } from 'vue';
import { message } from 'ant-design-vue';
import { exportTreeToExcel } from '@/utils/exportTreeExcel';

interface TreeItem {
  value: string;
  label: string;
  note?: string;
  children?: TreeItem[]
}

//级联选择器
const selectedValue = ref<string[]>([])
const treeData = ref<TreeItem[]>([
  {
    value: 'HY环境科技',
    label: 'HY环境科技',
    note: '-',
    children: [
        {
            value: '运营部',
            label: '运营部',
            note: '-',
            children: [{
                value: '人事部',
                label: '人事部',
                note: '-',
            }]
        },
        {
            value: '研发部',
            label: '研发部',
            note: '-',
        },
    ],
  }
])

const filterValue = ref<string[]>([''])
 
const handleSearch = (value: string[]) => {
  filterValue.value = value
}

const handleReset = (value: string[]) => {
  filterValue.value = value
}

//对话框
const addModalVisible = ref<boolean>(false)
const newNodeForm = ref({
  mode: 'root' as 'root' | 'child',
  label: '',
  value: '',
  note: '-',
  parentValue: undefined as string | undefined,
  parentLabel: ''
})
const treeTable = ref<any>(null)
const modeTitle = computed(() => newNodeForm.value.mode === 'root' ? '新增组织' : '添加下级组织')

const handleAddRoot = () => {
  newNodeForm.value = {
    mode: 'root',
    label: '',
    value: '',
    note: '-',
    parentValue: undefined,
    parentLabel: ''
  };
  addModalVisible.value = true
}

const handleAddChild = (parentNode: TreeItem) => {
  newNodeForm.value = {
    mode: 'child',
    label: '',
    value: '',
    note: parentNode.note as string,
    parentValue: parentNode.value,
    parentLabel: parentNode.label
  };
  addModalVisible.value = true
}

//验证节点唯一性
const validateNode = () => {
  if(!newNodeForm.value.label){
    message.error('请填写节点名称')
    return false
  }
  if(!newNodeForm.value.value){
    message.error('请填写节点值')
    return false
  }
  //检查值唯一性
  const isValueUnique = (nodes: TreeItem[]):boolean => {
    for(const node of nodes){
      if(node.value === newNodeForm.value.value)return false;
      if(node.children && !isValueUnique(node.children)) return false;
    }
    return true
  }
  if(!isValueUnique(treeData.value)){
    message.error(`节点值"${newNodeForm.value.value}"已存在`)
    return false;
  }
  return true
};

//查找节点
const findNode = (nodes: TreeItem[], value: string): TreeItem |null => {
  for(const node of nodes){
    if(node.value === value){
      return node
    }
    if(node.children){
      const found = findNode(node.children,value);
      if(found) return found
    } 
  }
  return null
};

const handleAddConfirm = () => {
  if(!validateNode()) return;

  const newNode: TreeItem = {
    value: newNodeForm.value.value,
    label: newNodeForm.value.label,
    note: newNodeForm.value.note
  }
  if(newNodeForm.value.mode === 'child' && newNodeForm.value.parentValue){
    //添加子节点
    const parent = findNode(treeData.value, newNodeForm.value.parentValue);
    if(parent){
      if(!parent.children){
        parent.children = [];
        parent.children.push(newNode)
      }
    }
  }else{
      //添加父节点
      treeData.value = [...treeData.value, newNode];
  }
  addModalVisible.value = false;
  message.success('新增节点成功')
}

const handleAddCancel = () => {
  addModalVisible.value = false
}

//导出数据

const exportData = () => {
  exportTreeToExcel(treeData.value,'树形数据导出',{
    columns:[
      {
        key: 'value', title: '组织标识'
      },
      {
        key: 'label', title: '组织名称'
      },
      {
        key: 'note', title: '备注'
      }
    ],
    indentSymbol: ' '
  })
}
</script>

<style scoped>
.about-head{
  display: flex;
  justify-content: space-between;
  padding: 10px;
}

</style>
